const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const config = require('./config/config');
const { testConnection } = require('./config/db');
const { ensureDirectoryExists } = require('./utils/fileUtils');

// 导入路由
const authRoutes = require('./routes/authRoutes');
const importRoutes = require('./routes/importRoutes');
const processRoutes = require('./routes/processRoutes');
const auditRoutes = require('./routes/auditRoutes');
const personnelRoutes = require('./routes/personnelRoutes');
const weaponRoutes = require('./routes/weaponRoutes');
const statsRoutes = require('./routes/statsRoutes');

const app = express();

// 中间件
app.use(cors());
app.use(morgan('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 静态文件服务（用于访问头像等）
app.use('/uploads', express.static('uploads'));
app.use(express.static('public'));

// 路由
app.use('/api/auth', authRoutes);
app.use('/api/import', importRoutes);
app.use('/api/process', processRoutes);
app.use('/api/audit', auditRoutes);
app.use('/api/personnel', personnelRoutes);
app.use('/api/weapons', weaponRoutes);
app.use(statsRoutes);

// 健康检查接口
app.get('/health', async (req, res) => {
  const dbConnected = await testConnection();
  
  res.json({
    status: 'ok',
    database: dbConnected ? 'connected' : 'disconnected',
    timestamp: new Date().toISOString()
  });
});

// 根路由
app.get('/', (req, res) => {
  res.json({
    name: '军事数据加工平台',
    version: '1.0.0',
    status: 'running',
    endpoints: {
      import: {
        uploadExcel: 'POST /api/import/excel',
        downloadTemplate: 'GET /api/import/template'
      },
      process: {
        batchProcess: 'POST /api/process/batch',
        processAll: 'POST /api/process/all',
        processSingle: 'POST /api/process/single/:id',
        getPending: 'GET /api/process/pending'
      },
      audit: {
        getPending: 'GET /api/audit/pending',
        getDetail: 'GET /api/audit/detail/:id',
        submit: 'POST /api/audit/submit',
        batchAudit: 'POST /api/audit/batch',
        getStatistics: 'GET /api/audit/statistics',
        getRecords: 'GET /api/audit/records'
      }
    }
  });
});


// 错误处理
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  res.status(500).json({
    success: false,
    message: err.message || '服务器内部错误'
  });
});

// 404处理
app.use((req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在'
  });
});

// 启动服务器
async function startServer() {
  try {
    // 确保必要的目录存在
    ensureDirectoryExists(config.upload.uploadDir);
    ensureDirectoryExists(config.upload.avatarDir);
    ensureDirectoryExists('./uploads/temp');
    ensureDirectoryExists('./uploads/thumbnails');

    // 测试数据库连接
    const dbConnected = await testConnection();
    if (!dbConnected) {
      console.error('⚠ 数据库连接失败，请检查配置');
      console.log('提示: 请运行 npm run init-db 初始化数据库');
    }

    // 启动服务
    const server = app.listen(config.port, () => {
      console.log('\n========================================');
      console.log('🚀 军事数据加工平台启动成功');
      console.log(`📡 服务地址: http://localhost:${config.port}`);
      console.log(`📊 健康检查: http://localhost:${config.port}/health`);
      console.log('========================================\n');
    });

    // 设置服务器超时时间为10分钟（数据处理需要较长时间）
    server.timeout = 600000;
  } catch (error) {
    console.error('启动失败:', error);
    process.exit(1);
  }
}

startServer();

module.exports = app;

